#include "xFileLoadPlugManager.h"




namespace XE	
{


	xFilePlug::xFilePlug()
	{

		xFilePlugManager::getSingleton().RegisterFilePlug(this);

	}

	  xFilePlug::~xFilePlug( )
	  {
		 xFilePlugManager::getSingleton().UnRegisterfilePlug(this);
	  }

	bool xFilePlug::CanLoad(const xString& fileName)
	{
		//-----get file  extend name 
      xString::size_type pos =  fileName.find_last_of('.');
		if(pos!=xString::npos)
		{
			xString extendname = fileName.substr(pos+1,fileName.length());
			xStringVector::iterator it = std::find(m_ExtendNameList.begin(),m_ExtendNameList.end(),extendname);
			if(it!=m_ExtendNameList.end())
			{
				return true;
			}
		
		}
		
		return false;
	}

	bool xFilePlug::CanSave(const xString& fileName)
	{
		return false;
	}









	xFilePlugManager* Singleton<xFilePlugManager>::ms_Singleton =NULL;

	xFilePlugManager::xFilePlugManager()
	{

	}


	bool xFilePlugManager::RegisterFilePlug(xFilePlug* pFilePlug)
	{
		if(pFilePlug==NULL)
			return false;
      if(HasFilePlug(pFilePlug))
		  return false;
	  m_FilePlugVector.push_back(pFilePlug);
		return true;
	}

	bool xFilePlugManager::UnRegisterfilePlug(xFilePlug* pFilePlug)
	{
		if(pFilePlug==NULL)
			return false;
		xFilePlugVector::iterator it =std::find(m_FilePlugVector.begin(),m_FilePlugVector.end(),pFilePlug);
		if(it!=m_FilePlugVector.end())
		{
			m_FilePlugVector.erase(it);
		}
		return true;

	}


	bool  xFilePlugManager::HasFilePlug(xFilePlug* pFilePlug)
	{
		if(pFilePlug==NULL)
			return false;
		xFilePlugVector::iterator it =std::find(m_FilePlugVector.begin(),m_FilePlugVector.end(),pFilePlug);
		if(it!=m_FilePlugVector.end())
			return true;
		return false;
	}

	xFilePlug* xFilePlugManager::FindLoadPlug(const xString& fileName)
	{

		xFilePlugVector::iterator it =m_FilePlugVector.begin();

		for(;it!=m_FilePlugVector.end();++it)
		{
			if((*it)->CanLoad(fileName))
				return *it;
		}
		return NULL;

	}


	bool  xFilePlugManager::LoadFile(const xString& filename,xSceneManager* SceneMgr)
	{
		
		xFilePlug* pLoader = FindLoadPlug(filename);
		if(pLoader==NULL)
			return false;
		return pLoader->LoadFile(filename,SceneMgr);
		
	}

}